package com.hooya.fa.eu.biz.service.impl;


import cn.hutool.core.util.StrUtil;
import com.hooya.fa.eu.biz.dao.entity.JcjlHistory;
import com.hooya.fa.eu.biz.dao.entity.TempKcjlDailyHy;
import com.hooya.fa.eu.biz.dao.entity.dto.TempKcjlDailyHyDTO;
import com.hooya.fa.eu.biz.dao.entity.dto.TransferRecordDTO;
import com.hooya.fa.eu.biz.dao.mapper.JcjlHistoryMapper;
import com.hooya.fa.eu.biz.dao.mapper.TempKcjlDailyHyMapper;
import com.hooya.fa.eu.biz.dao.mapper.TempKcjlDailyMapper;
import com.hooya.fa.eu.biz.dao.mapper.stk.*;
import com.hooya.fa.eu.biz.service.KcjlHyService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Data
@Slf4j
@Service
public class KcjlHyServiceImpl implements KcjlHyService {


	private static JdbcTemplate jdbcTemplate;

	// TODO -- 测试使用， 后续删除
	static {
		// 使用 Spring 提供的 DriverManagerDataSource
		DriverManagerDataSource dataSource = new DriverManagerDataSource();

		// 数据库驱动类 (根据数据库类型选择)
		dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

		// 数据库连接 URL (替换为你的数据库地址和库名)
		dataSource.setUrl("jdbc:mysql://localhost:3306/fa_eu?useUnicode=true&characterEncoding=utf8&useSSL=false");

		// 数据库用户名
		dataSource.setUsername("root");

		// 数据库密码
		dataSource.setPassword("root");
		jdbcTemplate = new JdbcTemplate(dataSource);

	}


	@Autowired
	private TempJcjlMapper tempJcjlMapper;

	@Autowired
	private TempPkpyMapper tempPkpyMapper;

	@Autowired
	private TempThjlMapper tempThjlMapper;

	@Autowired
	private TempXsjlMapper tempXsjlMapper;

	@Autowired
	private TempZyjlMapper tempZyjlMapper;

	@Autowired
	private TempKcjlDailyHyMapper tempKcjlDailyHyMapper;

	@Autowired
	private TempKcjlDailyMapper tempKcjlDailyMapper;

	@Autowired
	private JcjlHistoryMapper jcjlHistoryMapper;

	private final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

	// 从settings.py中导入的配置
	private final Map<String, String> ckCountryDict = new HashMap<>();
	private final Map<String, String> ABNORMAL_BELONGS = new HashMap<String, String>() {{
		put("HY-SCBXS22114494", "FDS-DE");
		put("HY-SCBXS21106017", "COSTWAY-PL");
		put("HY-SCBXS20044489", "FDS-DE");
		put("FRLT-220002NB", "COSTWAY-FR");
	}};
	private final Map<String, String> VIRTUAL_CK = new HashMap<>();
	private final Map<String, String> RESTOCK_PLACE_LIST = new HashMap<>();

	// TODO -- 这里面都是fa_eu.metawarehouse数据库中的数据，但是由于历史原因暂时采用这种形式使用
	// TODO -- 即使要改，也只是将这里的内容移植到sql语句中，得不偿失
	{
		// 初始化一些必要的配置
		ckCountryDict.put("EU01", "DE");
		ckCountryDict.put("EU02", "DE");
		ckCountryDict.put("EU99", "DE");
		ckCountryDict.put("EU98", "DE");
		ckCountryDict.put("EU97", "DE");
		ckCountryDict.put("EU96", "DE");
		ckCountryDict.put("EU生资库", "DE");
		ckCountryDict.put("EU03", "DE");
		ckCountryDict.put("EU04", "FR");
		ckCountryDict.put("EU95", "FR");
		ckCountryDict.put("EU94", "FR");
		ckCountryDict.put("EU05", "DE");
		ckCountryDict.put("EU06", "IT");
		ckCountryDict.put("EU07", "PL");
		ckCountryDict.put("EU93", "DE");
		ckCountryDict.put("EU92", "DE");
		ckCountryDict.put("EU91", "PL");
		ckCountryDict.put("EU90", "PL");
		ckCountryDict.put("EU89", "FR");
		ckCountryDict.put("EU88", "IT");
		ckCountryDict.put("EU87", "IT");
		ckCountryDict.put("EU86", "FR");
		ckCountryDict.put("EU08", "PL");
		ckCountryDict.put("EU10", "FR");
		ckCountryDict.put("EU09", "PL");
		ckCountryDict.put("EU101", "FR");
		ckCountryDict.put("EU71", "PL");
		ckCountryDict.put("EU70", "PL");
		ckCountryDict.put("EU85", "FR");
		ckCountryDict.put("EU79", "DE");
		ckCountryDict.put("EU78", "DE");
		ckCountryDict.put("EU11", "PL");
		ckCountryDict.put("EU72", "FR");
		ckCountryDict.put("EU100", "PL");
		ckCountryDict.put("EU102", "FR");
		ckCountryDict.put("EU103", "DE");
		ckCountryDict.put("EU104", "IT");
		ckCountryDict.put("EU105", "FR");
		ckCountryDict.put("EU73", "PL");
		ckCountryDict.put("EU201", "DE");
		ckCountryDict.put("EU202", "FR");
		ckCountryDict.put("EU203", "PL");
		ckCountryDict.put("EU204", "FR");
		ckCountryDict.put("EU205", "DE");
		ckCountryDict.put("EU206", "IT");
		ckCountryDict.put("EU207", "PL");
		ckCountryDict.put("EU208", "PL");
		ckCountryDict.put("EU209", "PL");
		ckCountryDict.put("EU106", "PL");
		ckCountryDict.put("EU107", "PL");
		ckCountryDict.put("EU108", "PL");
		ckCountryDict.put("EU84", "DE");
		ckCountryDict.put("EU109", "DE");
		ckCountryDict.put("EU110", "DE");
		ckCountryDict.put("EU112", "PL");
		ckCountryDict.put("EU111", "PL");
		ckCountryDict.put("EU114", "FR");
		ckCountryDict.put("EU120", "DE");
		ckCountryDict.put("EU113", "DE");
		ckCountryDict.put("EU83", "FR");
		ckCountryDict.put("EU115", "DE");
		ckCountryDict.put("EU116", "IT");
		ckCountryDict.put("EU117", "DE");
		ckCountryDict.put("EU80", "IT");
		ckCountryDict.put("EU118", "IT");
		ckCountryDict.put("EU81", "IT");
		ckCountryDict.put("EU82", "IT");
		ckCountryDict.put("EU119", "PL");
		ckCountryDict.put("EU121", "PL");
		ckCountryDict.put("EU122", "FR");
		ckCountryDict.put("EU123", "PL");
		ckCountryDict.put("EU124", "PL");
		ckCountryDict.put("EU125", "PL");
		ckCountryDict.put("EU15", "DE");
		ckCountryDict.put("EU12", "IT");
		ckCountryDict.put("EU134", "IT");
		ckCountryDict.put("EU136", "DE");

		// 初始化VIRTUAL_CK映射表
		VIRTUAL_CK.put("EU100", "EU09");
		VIRTUAL_CK.put("EU102", "EU10");
		VIRTUAL_CK.put("EU103", "EU05");
		VIRTUAL_CK.put("EU104", "EU06");
		VIRTUAL_CK.put("EU105", "EU10");
		VIRTUAL_CK.put("EU106", "EU09");
		VIRTUAL_CK.put("EU107", "EU11");
		VIRTUAL_CK.put("EU108", "EU07");
		VIRTUAL_CK.put("EU109", "EU01");
		VIRTUAL_CK.put("EU110", "EU05");
		VIRTUAL_CK.put("EU112", "EU07");
		VIRTUAL_CK.put("EU111", "EU11");
		VIRTUAL_CK.put("EU114", "EU10");
		VIRTUAL_CK.put("EU120", "EU05");
		VIRTUAL_CK.put("EU117", "EU01");
		VIRTUAL_CK.put("EU118", "EU06");
		VIRTUAL_CK.put("EU119", "EU09");
		VIRTUAL_CK.put("EU121", "EU11");
		VIRTUAL_CK.put("EU123", "EU07");
		VIRTUAL_CK.put("EU124", "EU09");
		VIRTUAL_CK.put("EU125", "EU11");

		// 初始化RESTOCK_PLACE_LIST映射表
		RESTOCK_PLACE_LIST.put("EU97", "EU01");
		RESTOCK_PLACE_LIST.put("EU96", "EU01");
		RESTOCK_PLACE_LIST.put("EU95", "EU04");
		RESTOCK_PLACE_LIST.put("EU94", "EU04");
		RESTOCK_PLACE_LIST.put("EU93", "EU05");
		RESTOCK_PLACE_LIST.put("EU92", "EU05");
		RESTOCK_PLACE_LIST.put("EU91", "EU07");
		RESTOCK_PLACE_LIST.put("EU90", "EU07");
		RESTOCK_PLACE_LIST.put("EU88", "EU06");
		RESTOCK_PLACE_LIST.put("EU87", "EU06");
		RESTOCK_PLACE_LIST.put("EU101", "EU10");
		RESTOCK_PLACE_LIST.put("EU71", "EU09");
		RESTOCK_PLACE_LIST.put("EU70", "EU09");
		RESTOCK_PLACE_LIST.put("EU72", "EU10");
	}


	// 主要处理逻辑--生成Tempkcjl_dality_hy数据
	public void KcjlHy(String startDate, String endDate) {

		// 生成日期列表
		List<String> dateList = generateDateList(startDate, endDate);

		// 获取各种数据
		Map<String, List<?>> data = getData(startDate, endDate);

		// 直接获取已经转换好的最终DTO数据
		List<TempKcjlDailyHyDTO> jcjldata = (List<TempKcjlDailyHyDTO>) data.get("jcjldata");
		List<TempKcjlDailyHyDTO> pkpydata = (List<TempKcjlDailyHyDTO>) data.get("pkpydata");
		List<TempKcjlDailyHyDTO> thjldata = (List<TempKcjlDailyHyDTO>) data.get("thjldata");
		List<TempKcjlDailyHyDTO> xsjldata = (List<TempKcjlDailyHyDTO>) data.get("xsjldata");
		List<TransferRecordDTO> zyjldata = (List<TransferRecordDTO>) data.get("zyjldata");
		List<TempKcjlDailyHy> kcjl_hy = (List<TempKcjlDailyHy>) data.get("hydata");


		// 获取进仓历史记录
		List<JcjlHistory> jcjlhis = getJcjlHis();

		// 处理每条日期
		for (String date : dateList) {
			log.info("处理日期: {}", date);

			// 获取最后的进仓历史记录--//TODO 检查原因 -- 这里去重时少了一个条数据 -- 找到了，由于py中的非正常belongs替换失效
			List<TempKcjlDailyHyDTO> jcjl_last = getLastJcjlhis(jcjlhis, date);

			// 过滤当天的数据
			List<TempKcjlDailyHyDTO> single_jcjldata = jcjldata.stream()
					.filter(r -> date.equals(r.getDate()))
					.collect(Collectors.toList());

			List<TempKcjlDailyHyDTO> single_pkpydata = pkpydata.stream()
					.filter(r -> date.equals(r.getDate()))
					.collect(Collectors.toList());

			List<TempKcjlDailyHyDTO> single_thjldata = thjldata.stream()
					.filter(r -> date.equals(r.getDate()))
					.collect(Collectors.toList());

			List<TempKcjlDailyHyDTO> single_xsjldata = xsjldata.stream()
					.filter(r -> date.equals(r.getDate()))
					.collect(Collectors.toList());

			List<TransferRecordDTO> single_zyjldata = zyjldata.stream()
					.filter(r -> date.equals(r.getDate()))
					.collect(Collectors.toList());

			// 处理数据
			kcjl_hy = getFinalData(
					single_jcjldata,
					single_pkpydata,
					single_thjldata,
					single_xsjldata,
					single_zyjldata,
					jcjl_last,
					kcjl_hy
			);

			// 过滤掉sl为0的记录
			kcjl_hy = kcjl_hy.stream()
					.filter(r -> r.getSl() != 0)
					.collect(Collectors.toList());

			// 设置日期
			kcjl_hy.forEach(record -> record.setDate(date));

			// 插入数据到数据库
			log.info("kcjl_hy的数量为：{}", kcjl_hy.size());


			// TODO -- 后续取消注释

//            insertSql(kcjl_hy);
		}
	}


	private List<String> generateDateList(String startDate, String endDate) {
		List<String> dateList = new ArrayList<>();
		Date startDateObj = null;
		Date endDateObj = null;
		try {
			startDateObj = DATE_FORMAT.parse(startDate);
			endDateObj = DATE_FORMAT.parse(endDate);
		} catch (ParseException e) {
			throw new RuntimeException("generateDateList方法中的日期类型转换出错", e);
		}

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startDateObj);

		while (calendar.getTime().before(endDateObj)) {
			dateList.add(DATE_FORMAT.format(calendar.getTime()));
			calendar.add(Calendar.DAY_OF_MONTH, 1);
		}
		return dateList;
	}

	// 获取各种数据
	private Map<String, List<?>> getData(String startDate, String endDate) {
		Map<String, List<?>> result = new HashMap<>();

		// 进仓记录
		List<TempKcjlDailyHyDTO> jcjldata = tempJcjlMapper.getJcjlData(startDate, endDate);

		// 盘亏盘盈
		List<TempKcjlDailyHyDTO> pkpydata = tempPkpyMapper.getPkpyData(startDate, endDate);

		// 退货记录
		List<TempKcjlDailyHyDTO> thjldata = tempThjlMapper.getThjlData(startDate, endDate, "FDS%", "COSTWAY%")
				.stream()
				.map(this::alterbelongs)
				.collect(Collectors.toList());


		// 聚合相同记录
		thjldata = aggregateRecords(thjldata);

		// 销售记录
		List<TempKcjlDailyHyDTO> xsjldata = tempXsjlMapper.getXsjlData(startDate, endDate, "FDS%", "COSTWAY%")
				.stream()
				.map(this::alterbelongs)
				.collect(Collectors.toList());
		// 聚合相同记录
		xsjldata = aggregateRecords(xsjldata);

		// 转运记录
		List<TransferRecordDTO> zyjldata = tempZyjlMapper.getZyjlData(startDate, endDate, "HW63759WH");


		// 初始库存货源
		Date hydateDate = null;
		try {
			hydateDate = new Date(DATE_FORMAT.parse(startDate).getTime() - 24 * 60 * 60 * 1000);
		} catch (ParseException e) {
			throw new RuntimeException("getData中的日期格式转换出错", e);
		}
		String hydate = DATE_FORMAT.format(hydateDate);
		List<TempKcjlDailyHy> hydata = tempKcjlDailyHyMapper.getHyData(hydate);

		result.put("jcjldata", jcjldata);
		result.put("pkpydata", pkpydata);
		result.put("thjldata", thjldata);
		result.put("xsjldata", xsjldata);
		result.put("zyjldata", zyjldata);
		result.put("hydata", hydata);

		return result;
	}

	// 处理belongs字段
	private TempKcjlDailyHyDTO alterbelongs(TempKcjlDailyHyDTO record) {
		if ("FDS".equals(record.getBelongs())) {
			record.setBelongs("FDS-" + ckCountryDict.getOrDefault(record.getPlace(), ""));
		} else if ("COSTWAY".equals(record.getBelongs())) {
			record.setBelongs("COSTWAY-" + ckCountryDict.getOrDefault(record.getPlace(), ""));
		}
		return record;
	}

	// 聚合相同记录
	private List<TempKcjlDailyHyDTO> aggregateRecords(List<TempKcjlDailyHyDTO> records) {
		Map<String, TempKcjlDailyHyDTO> aggregatedMap = new HashMap<>();

		for (TempKcjlDailyHyDTO record : records) {
			String key = record.getCpbh() + "_" + record.getPlace() + "_" + record.getBelongs() + "_" + record.getDate();
			if (aggregatedMap.containsKey(key)) {
				TempKcjlDailyHyDTO existingRecord = aggregatedMap.get(key);
				existingRecord.setSl(existingRecord.getSl() + record.getSl());
			} else {
				aggregatedMap.put(key, record);
			}
		}

		return new ArrayList<>(aggregatedMap.values());
	}

	// 获取进仓历史记录
	private List<JcjlHistory> getJcjlHis() {

		//查询+去重
		List<JcjlHistory> jcjlhis = jcjlHistoryMapper.getJcjlHistory()
				.stream()
				.distinct()
				.collect(Collectors.toList());


		// 处理异常belongs
		jcjlhis.forEach(dto -> {
			if (dto.getBelongs() == null || dto.getBelongs().isEmpty()) {
				String hthm = dto.getHthm();
				if (ABNORMAL_BELONGS.containsKey(hthm)) {
					dto.setBelongs(ABNORMAL_BELONGS.get(hthm));
				}
			}
			//  TODO -- 别忘了取消注释
//            log.info("处理异常belongs: {} , 其belongs发生变更-已被ABNORMAL_BELONGS进行替换", dto);
		});

		// 处理日期在2019-08-28之前的记录
		jcjlhis.forEach(dto -> {
			try {
				if (dto.getHtrq() != null && !dto.getHtrq().isEmpty()) {
					Date recordDate = DATE_FORMAT.parse(dto.getHtrq());
					Date cutoffDate = DATE_FORMAT.parse("2019-08-28");
					if (recordDate.before(cutoffDate)) {
						dto.setBelongs("FDS-DE");
					}
				}
			} catch (ParseException e) {
				log.error("解析日期失败: {}", dto.getHtrq(), e);
			}
		});

//        int i = 0;
//        for (JcjlHistory jcjlhi : jcjlhis) {
//            if (jcjlhi.getBelongs() == null || jcjlhi.getBelongs().isEmpty()) {
//                log.info("jcjlhis中的belongs为空: {}", jcjlhi);
//                i++;
//            }
//        }
//        log.info("jcjlhis中的belongs为空的记录数量为: {}", i);

		// 过滤belongs为空的记录
		jcjlhis = jcjlhis.stream()
				.filter(dto -> dto.getBelongs() != null)
				.collect(Collectors.toList());

		// 处理place映射
		jcjlhis.forEach(dto -> {
			String place = dto.getPlace();
			if (place != null && VIRTUAL_CK.containsKey(place)) {
				dto.setPlace(VIRTUAL_CK.get(place));
			}
		});

		// 过滤restockPlaceList中的place
		jcjlhis = jcjlhis.stream()
				.filter(dto -> !RESTOCK_PLACE_LIST.containsKey(dto.getPlace()))
				.collect(Collectors.toList());

		return jcjlhis;
	}

	// 处理进仓记录
	private List<TempKcjlDailyHy> addjcjl(List<TempKcjlDailyHyDTO> jcjldata, List<TempKcjlDailyHy> kcjl_hy) {
		for (TempKcjlDailyHyDTO record : jcjldata) {
			boolean found = false;
			for (TempKcjlDailyHy kcRecord : kcjl_hy) {
				if (kcRecord.getCpbh().equals(record.getCpbh()) &&
						kcRecord.getPlace().equals(record.getPlace()) &&
						kcRecord.getBelongs().equals(record.getBelongs()) &&
						kcRecord.getHtrq().equals(record.getDate()) &&
						kcRecord.getHy().equals(record.getHy())) {
					kcRecord.setSl(kcRecord.getSl() + record.getSl());
					found = true;
					break;
				}
			}
			if (!found) {
				kcjl_hy.add(new TempKcjlDailyHy(record.getCpbh(), record.getPlace(), record.getSl(), record.getBelongs(), record.getHy(), record.getDate(), ""));
				//TODO -- 别忘了取消注释
//				log.info("添加新的库存记录: {}", record);
			}
		}
		return kcjl_hy;
	}

	// 处理盘亏盘盈记录
	private List<TempKcjlDailyHy> addpkpy(List<TempKcjlDailyHyDTO> pkpydata, List<TempKcjlDailyHy> kcjl_hy, List<TempKcjlDailyHyDTO> jcjl_last) {
		if (pkpydata.isEmpty()) {
			return kcjl_hy;
		}

		for (TempKcjlDailyHyDTO record : pkpydata) {
			String cpbh = record.getCpbh();
			String place = record.getPlace();
			String belongs = record.getBelongs();
			int sl = record.getSl() == null ? 0 : record.getSl();

			// 排除特定的cpbh
			if (Arrays.asList("HW59104", "KC49465", "HW64114GR", "HW63759WH").contains(cpbh)) {
				continue;
			}

			// 查找当前库存
			List<TempKcjlDailyHy> matchingRecords = kcjl_hy.stream()
					.filter(kc -> kc.getCpbh().equals(cpbh) &&
							kc.getPlace().equals(place) &&
							kc.getBelongs().equals(belongs))
					.collect(Collectors.toList());

			if (!matchingRecords.isEmpty()) {
				if (matchingRecords.size() > 1) {
					// 检查是否有相同的htrq
					Map<String, List<TempKcjlDailyHy>> groupedByHtrq = matchingRecords.stream()
							.collect(Collectors.groupingBy(TempKcjlDailyHy::getHtrq));

					if (groupedByHtrq.size() == 1 || hasMultipleGroupsWithSizeGreaterThanOne(groupedByHtrq)) {
						// 逐个扣减
						for (TempKcjlDailyHy kc : matchingRecords) {
							if (kc.getSl() - sl >= 0) {
								kc.setSl(kc.getSl() - sl);
								break;
							} else {
								sl = sl - kc.getSl();
								kc.setSl(0);
							}
						}
					} else {
						// 日期不同，取最新日期的记录扣减
						String lastdate = matchingRecords.stream()
								.map(TempKcjlDailyHy::getHtrq)
								.max(Comparator.naturalOrder())
								.orElse(null);

						for (TempKcjlDailyHy kc : matchingRecords) {
							if (kc.getHtrq().equals(lastdate)) {
								kc.setSl(kc.getSl() - sl);
								break;
							}
						}
					}
				} else {
					// 只有一条记录，直接扣减
					matchingRecords.get(0).setSl(matchingRecords.get(0).getSl() - sl);
				}
			} else {
				// 期初无库存，从历史记录中查找
				TempKcjlDailyHyDTO historyRecord = findHistoryRecordForCpbhAndBelongs(cpbh, belongs, jcjl_last);
				String hy = historyRecord != null ? historyRecord.getHy() : "";
				String date = historyRecord != null ? historyRecord.getDate() : "";

				// 添加负库存记录
				TempKcjlDailyHy newRecord = new TempKcjlDailyHy();
				newRecord.setCpbh(cpbh);
				newRecord.setPlace(place);
				newRecord.setSl(-sl);
				newRecord.setBelongs(belongs);
				newRecord.setHy(hy);
				newRecord.setHtrq(date);
				kcjl_hy.add(newRecord);
			}
		}

		return kcjl_hy;
	}

	// 检查是否有多个分组的大小大于1
	private boolean hasMultipleGroupsWithSizeGreaterThanOne(Map<String, List<TempKcjlDailyHy>> groupedByHtrq) {
		long count = groupedByHtrq.values().stream()
				.filter(list -> list.size() > 1)
				.count();
		return count > 1;
	}

	// 查找指定cpbh和belongs的历史记录
	private TempKcjlDailyHyDTO findHistoryRecordForCpbhAndBelongs(String cpbh, String belongs, List<TempKcjlDailyHyDTO> jcjl_last) {
		if (belongs != null && belongs.contains("-")) {
			String belongsPrefix = belongs.split("-")[0];
			List<TempKcjlDailyHyDTO> matchingRecords = jcjl_last.stream()
					.filter(kc -> kc.getCpbh().equals(cpbh) &&
							kc.getBelongs() != null &&
							kc.getBelongs().contains(belongsPrefix))
					.collect(Collectors.toList());
			if (!matchingRecords.isEmpty()) {
				return matchingRecords.get(0);
			}
		}

		// 如果没有找到，尝试只匹配cpbh
		return jcjl_last.stream()
				.filter(kc -> kc.getCpbh().equals(cpbh))
				.findFirst()
				.orElse(null);
	}

	// 处理退货记录
	private List<TempKcjlDailyHy> addthjl(List<TempKcjlDailyHyDTO> thjldata, List<TempKcjlDailyHy> kcjl_hy, List<TempKcjlDailyHyDTO> jcjl_last) {
		for (TempKcjlDailyHyDTO record : thjldata) {
			String cpbh = record.getCpbh();
			String place = record.getPlace();
			String belongs = record.getBelongs();
			int sl = record.getSl() == null ? 0 : record.getSl();

			// 查找历史记录
			TempKcjlDailyHyDTO historyRecord = findHistoryRecordForCpbhAndBelongs(cpbh, belongs, jcjl_last);

			if (historyRecord != null) {
				String hy = historyRecord.getHy();
				String date = historyRecord.getDate();

				// 查找是否已存在相同记录
				boolean found = false;
				for (TempKcjlDailyHy kcRecord : kcjl_hy) {
					if (kcRecord.getCpbh().equals(cpbh) &&
							kcRecord.getPlace().equals(place) &&
							kcRecord.getBelongs().equals(belongs) &&
							kcRecord.getHy().equals(hy)) {
						kcRecord.setSl(kcRecord.getSl() + sl);
						found = true;
						break;
					}
				}

				if (!found) {
					TempKcjlDailyHy newRecord = new TempKcjlDailyHy();
					newRecord.setCpbh(cpbh);
					newRecord.setPlace(place);
					newRecord.setSl(sl);
					newRecord.setBelongs(belongs);
					newRecord.setHy(hy);
					newRecord.setHtrq(date);
					kcjl_hy.add(newRecord);
				}
			}
		}

		return kcjl_hy;
	}

	// 处理转运记录
	private List<TempKcjlDailyHy> addzyjl(List<TransferRecordDTO> zyjldata, List<TempKcjlDailyHy> kcjl_hy) {
		if (zyjldata.isEmpty()) {
			return kcjl_hy;
		}

		// 创建任务列表副本，以便在处理过程中移除已处理的任务
		List<TransferRecordDTO> tasks = new ArrayList<>(zyjldata);

		// 按cpbh分组
		Map<String, List<TransferRecordDTO>> cpbhGroups = tasks.stream()
				.collect(Collectors.groupingBy(TransferRecordDTO::getCpbh));

		// 对每组任务进行排序
		List<TransferRecordDTO> sortedTasks = new ArrayList<>();
		for (Map.Entry<String, List<TransferRecordDTO>> entry : cpbhGroups.entrySet()) {
			List<TransferRecordDTO> group = entry.getValue();
			if (group.size() == 1) {
				sortedTasks.addAll(group);
				continue;
			}

			// 计算每个zlck在zcck中出现的次数 (修正逻辑以匹配Python)
			Map<String, Integer> zcckCounter = new HashMap<>();
			for (TransferRecordDTO task : group) {
				String zcck = task.getZcck();
				// 计算与当前任务有相同zcck的任务数量
				int count = (int) group.stream().filter(t -> t.getZcck().equals(zcck)).count();
				zcckCounter.put(task.getZlck(), count);
			}

			// 按照zcck出现次数和原始顺序排序
			List<TransferRecordDTO> sortedGroup = group.stream()
					.sorted((task1, task2) -> {
						int count1 = zcckCounter.getOrDefault(task1.getZlck(), 0);
						int count2 = zcckCounter.getOrDefault(task2.getZlck(), 0);
						// 按照出现次数降序排列，如果次数相同则保持原始顺序
						int result = Integer.compare(count2, count1);
						if (result == 0) {
							// 保持原始顺序
							return Integer.compare(group.indexOf(task1), group.indexOf(task2));
						}
						return result;
					})
					.collect(Collectors.toList());

			sortedTasks.addAll(sortedGroup);
		}

		// 使用while循环处理任务，并在处理完成后移除任务
		int i = 0;
		while (i < sortedTasks.size()) {
			TransferRecordDTO task = sortedTasks.get(i);
			String cpbh = task.getCpbh();
			String zcck = task.getZcck();
			String zlck = task.getZlck();
			String frombelongs = task.getFrombelongs();
			String tobelongs = task.getTobelongs();
			int sl = task.getSl() == null ? 0 : task.getSl();

			// 查找转出仓库的库存
			List<TempKcjlDailyHy> zcckKc = kcjl_hy.stream()
					.filter(kc -> kc.getPlace().equals(zcck) &&
							kc.getCpbh().equals(cpbh) &&
							kc.getBelongs().equals(frombelongs))
					.collect(Collectors.toList());

			if (zcckKc.isEmpty()) {
				i++;
				continue;
			}

			// 检查库存是否足够
			int totalSl = zcckKc.stream().mapToInt(TempKcjlDailyHy::getSl).sum();
			if (totalSl < sl) {
				i++;
				continue;
			}

			// 按htrq排序，处理可能为null的情况
			zcckKc.sort(Comparator.comparing(TempKcjlDailyHy::getHtrq,
					Comparator.nullsLast(Comparator.naturalOrder())));

			int remainingSl = sl;
			for (TempKcjlDailyHy kc : zcckKc) {
				if (remainingSl == 0) {
					break;
				}

				String hy = kc.getHy();
				String htrq = kc.getHtrq();
				int kcsl = kc.getSl();

				if (kcsl >= remainingSl) {
					// 扣减库存
					kc.setSl(kcsl - remainingSl);
					// 添加到转入仓库
					addToTargetWarehouse(kcjl_hy, cpbh, zlck, tobelongs, remainingSl, hy, htrq);
					remainingSl = 0;
				} else {
					// 扣减全部库存
					kc.setSl(0);
					// 添加到转入仓库
					addToTargetWarehouse(kcjl_hy, cpbh, zlck, tobelongs, kcsl, hy, htrq);
					remainingSl -= kcsl;
				}
			}

			// 处理完成后从列表中移除该任务（对应Python的tasks.pop(i)）
			sortedTasks.remove(i);
		}

		return kcjl_hy;
	}

	// 添加到目标仓库
	private void addToTargetWarehouse(List<TempKcjlDailyHy> kcjl_hy, String cpbh, String zlck, String tobelongs, int sl, String hy, String htrq) {
		boolean found = false;
		for (TempKcjlDailyHy kcRecord : kcjl_hy) {
			if (kcRecord.getCpbh().equals(cpbh) &&
					kcRecord.getPlace().equals(zlck) &&
					kcRecord.getBelongs().equals(tobelongs) &&
					kcRecord.getHy().equals(hy)) {
				kcRecord.setSl(kcRecord.getSl() + sl);
				found = true;
				break;
			}
		}

		if (!found) {
			TempKcjlDailyHy newRecord = new TempKcjlDailyHy();
			newRecord.setCpbh(cpbh);
			newRecord.setPlace(zlck);
			newRecord.setSl(sl);
			newRecord.setBelongs(tobelongs);
			newRecord.setHy(hy);
			newRecord.setHtrq(htrq);
			kcjl_hy.add(newRecord);
		}
	}

	// 处理销售记录
	private List<TempKcjlDailyHy> addxsjl(List<TempKcjlDailyHyDTO> xsjldata, List<TempKcjlDailyHy> kcjl_hy) {
		for (TempKcjlDailyHyDTO record : xsjldata) {
			String cpbh = record.getCpbh();
			String belongs = record.getBelongs();
			String place = record.getPlace();
			int sl = record.getSl() == null ? 0 : record.getSl();

			// 查找匹配的库存记录，按cpbh、belongs、place过滤（与Python版本保持一致）
			List<TempKcjlDailyHy> matchingRecords = kcjl_hy.stream()
					.filter(kc -> kc.getCpbh().equals(cpbh) &&
							kc.getBelongs().equals(belongs) &&
							kc.getPlace().equals(place))
					.sorted(Comparator.comparing(TempKcjlDailyHy::getHtrq,
							Comparator.nullsLast(Comparator.naturalOrder())))
					.collect(Collectors.toList());

			int remainingSl = sl;
			for (TempKcjlDailyHy kc : matchingRecords) {
				if (remainingSl == 0) {
					break;
				}

				int kcsl = kc.getSl();
				if (kcsl >= remainingSl) {
					kc.setSl(kcsl - remainingSl);
					remainingSl = 0;
				} else {
					kc.setSl(0);
					remainingSl -= kcsl;
				}
			}
			record.setSl(remainingSl);
		}

		return kcjl_hy;
	}

	// 获取最后进仓历史记录
	private List<TempKcjlDailyHyDTO> getLastJcjlhis(List<JcjlHistory> jcjlhis, String date) {
		try {
			Date cutoffDate = DATE_FORMAT.parse(date);

			// 过滤日期小于指定日期的记录
			List<JcjlHistory> newjcjlhis = jcjlhis.stream()
					.filter(dto -> {
						try {
							Date recordDate = DATE_FORMAT.parse(dto.getHtrq());
							return recordDate.before(cutoffDate);
						} catch (ParseException e) {
							return false;
						}
					})
					.collect(Collectors.toList());

			// 提取belongs第一部分并创建新的列表
			List<ProcessedJcjlHistory> processedList = new ArrayList<>();
			for (JcjlHistory dto : newjcjlhis) {
				ProcessedJcjlHistory processedDto = getProcessedJcjlHistory(dto);
				processedList.add(processedDto);
			}

			// 按htrq排序
			processedList.sort(Comparator.comparing(ProcessedJcjlHistory::getHtrq,
					Comparator.nullsLast(Comparator.naturalOrder())));

			// 去重，保留最新的记录
			Map<String, ProcessedJcjlHistory> uniqueRecords = new LinkedHashMap<>();
			for (ProcessedJcjlHistory dto : processedList) {
				String key = dto.getCpbh() + "|" + (StrUtil.isEmpty(dto.getNewBelongs()) ? "null" : dto.getNewBelongs());
				uniqueRecords.put(key, dto);
			}

			// 转换为TempKcjlDailyHyDTO
			List<TempKcjlDailyHyDTO> result = new ArrayList<>();
			for (ProcessedJcjlHistory dto : uniqueRecords.values()) {
				TempKcjlDailyHyDTO record = new TempKcjlDailyHyDTO();
				record.setCpbh(dto.getCpbh());
				record.setBelongs(dto.getNewBelongs());
				record.setHy(dto.getHthm());
				record.setDate(dto.getHtrq());
				result.add(record);
			}

			return result;
		} catch (ParseException e) {
			log.error("解析日期失败: {}", date, e);
			return new ArrayList<>();
		}
	}

	private static @NotNull ProcessedJcjlHistory getProcessedJcjlHistory(JcjlHistory dto) {
		ProcessedJcjlHistory processedDto = new ProcessedJcjlHistory();
		processedDto.setCpbh(dto.getCpbh());
		processedDto.setHthm(dto.getHthm());
		processedDto.setHtrq(dto.getHtrq());
		// 提取belongs第一部分
		String belongs = dto.getBelongs();
		if (belongs.contains("-")) {
			processedDto.setNewBelongs(belongs.split("-")[0]);
		} else {
			processedDto.setNewBelongs(belongs);
		}
		return processedDto;
	}

	// 内部辅助类，用于处理历史记录（与Python版本的处理逻辑保持一致）
	@Data
	private static class ProcessedJcjlHistory {
		private String cpbh;
		private String hthm;
		private String htrq;
		private String newBelongs;
	}

	// 按顺序处理各种数据
	private List<TempKcjlDailyHy> getFinalData(List<TempKcjlDailyHyDTO> jcjldata, List<TempKcjlDailyHyDTO> pkpydata,
											   List<TempKcjlDailyHyDTO> thjldata, List<TempKcjlDailyHyDTO> xsjldata,
											   List<TransferRecordDTO> zyjldata, List<TempKcjlDailyHyDTO> jcjl_last,
											   List<TempKcjlDailyHy> kcjl_hy) {
		// 逻辑顺序 jcjldata>pkpydata>thjldata>zyjldata>xsjldata
		kcjl_hy = addjcjl(jcjldata, kcjl_hy);
		kcjl_hy = addpkpy(pkpydata, kcjl_hy, jcjl_last);
		kcjl_hy = addthjl(thjldata, kcjl_hy, jcjl_last);
		kcjl_hy = addzyjl(zyjldata, kcjl_hy);
		kcjl_hy = addxsjl(xsjldata, kcjl_hy);
		return kcjl_hy;
	}

	// 插入数据到数据库
	private void insertSql(List<TempKcjlDailyHy> data) {
		try {
			if (!data.isEmpty())
				tempKcjlDailyHyMapper.batchInsert(data);
			else log.info("没有数据需要插入");
		} catch (Exception e) {
			log.error("插入数据失败", e);
		}
	}


}
